<template>
  <div>
    <Row class="drive-chose-row attrpage">
      <Col span="7">
        <div class="drive-head">
          <h3>分组</h3>
          <div class="add-btn" @click="addGroup()">添加分组</div>
        </div>
        <div class="drive-list">
          <RadioGroup @change="cattap" v-model:value="mrdriveId" name="radioGroup">
            <Radio v-for="item in listData" :key="item.id" class="flexRow" :value="item.id">
              <div class="flexc">
                <div class="item_left" :title="item.group_name">{{ item.group_name }}</div>
                <div class="item_right">
                  <a class="groupedite" @click.stop="editeGroup(item)" v-if="item.group_level != 1"
                    >编辑</a
                  >
                  <a class="groupedite" @click.stop="delGroup(item.id)" v-if="item.group_level != 1"
                    >删除</a
                  >
                </div>
              </div>
            </Radio>
          </RadioGroup>
        </div>
      </Col>
      <Col span="17">
        <div class="drive-head">
          <h3>属性</h3>
          <div class="add-attrs">
            <div class="arritem" @click="batchUpload">批量导入</div>
            <div class="arritem" @click="toAddAttr">添加属性</div>
          </div>
        </div>
        <a-table
          @change="handleTableChange"
          :loading="listLoading"
          :columns="columns"
          :data-source="dataSource"
          :scroll="{ x: 500, y: 300 }"
          bordered
          size="small"
          :pagination="ipagination"
        >
          <template #disable="{ record }">
            <a-tag :color="record.disable == 0 ? 'success' : 'error'">
              {{ record.disable == 0 ? '启用' : '禁用' }}
            </a-tag>
          </template>
          <template #action="{ record }">
            <a-tooltip placement="bottom">
              <template #title>
                <span>编辑</span>
              </template>
              <a style="margin-right: 16px">
                <FormOutlined @click.stop="openEdit(record)" />
              </a>
            </a-tooltip>
            <a-popconfirm :title="`确认删除属性:${record.name}吗？`" @confirm="openDelete(record)">
              <a-tooltip placement="bottom">
                <template #title>
                  <span>删除</span>
                </template>
                <DeleteOutlined style="color: #ed6f6f" />
              </a-tooltip>
            </a-popconfirm>
          </template>
        </a-table>
      </Col>
    </Row>
    <AttrGroupDialog
      @register="registerAttrGroupModel"
      @submit="submitSuccess"
      :device_mode_id="device_mode_id"
    />

    <Batchuploaddialog
      @register="registerBatchuploadd"
      :attribute_group_id="mrdriveId"
      :protocol_type="protocol_type"
      @importsuccess="importSuccess"
    />

    <attributeDialog @success="submitSuccess" ref="attributeDialogRef" v-if="reloadDialog" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, onBeforeMount, reactive, nextTick } from 'vue';
  import { Row, Col, Radio, RadioGroup } from 'ant-design-vue';
  import { BasicTable, TableAction } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import AttrGroupDialog from './attrGroupdialog.vue';

  import attributeDialog from './attributeDialog.vue';
  import { DeleteOutlined, FormOutlined } from '@ant-design/icons-vue';
  import Batchuploaddialog from './Batchuploaddialog.vue';
  import { getAttrList, getAttrTableData } from './attrData';
  import {
    getModelAttrList,
    getModelGroupList,
    delModelAttrList,
    delAddModelGroup,
  } from '/@/api/sys/gateway/gateway';

  import { useMessage } from '/@/hooks/web/useMessage';

  interface AttrGroupModel {
    name: string;
  }

  const columns = [
    {
      title: '属性名称',
      width: 260,
      dataIndex: 'name',
      key: 'name',
      align: 'center',
      ellipsis: true,
    },
    { title: '自编码', width: 100, dataIndex: 'tag', key: 'tag', align: 'center' },
    { title: '数据类型', dataIndex: 'data_type', key: 'data_type', width: 80, align: 'center' },
    {
      title: '状态',
      dataIndex: 'disable',
      key: 'disable',
      width: 60,
      align: 'center',
      slots: { customRender: 'disable' },
    },
    {
      title: '描述',
      dataIndex: 'describe',
      key: 'describe',
      width: 150,
      align: 'center',
      ellipsis: true,
    },

    {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      align: 'center',
      width: 90,
      slots: { customRender: 'action' },
    },
  ];

  export default defineComponent({
    components: {
      FormOutlined,
      DeleteOutlined,
      Row,
      Col,
      BasicTable,
      TableAction,
      Radio,
      RadioGroup,
      AttrGroupDialog,
      Batchuploaddialog,
      attributeDialog,
    },
    props: ['protocol_type', 'device_mode_id'],
    setup(prop) {
      let listData = ref([]);
      let protocol_type = ref();
      let device_mode_id = ref();
      device_mode_id.value = prop.device_mode_id;
      protocol_type.value = prop.protocol_type;
      const attributeDialogRef = ref();

      const [registerAttrGroupModel, { openModal: openAttrGroupModal }] = useModal();

      const [registerBatchuploadd, { openModal: openBatchuploadd }] = useModal();
      const { createMessage, createConfirm } = useMessage();
      let tableData = ref([]);
      let mrdriveId = ref();
      let reloadDialog = ref(true);

      //分页参数
      const ipagination = reactive({
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '30', '50'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条';
        },
        showSizeChanger: true,
        total: 0,
      });
      //分页参数
      const listQuery = reactive({
        page: 1,
        page_size: 10,
        group_id: '',
      });
      //切换分页
      function handleTableChange(pagin) {
        ipagination.current = pagin.current;
        ipagination.total = pagin.total;
        listQuery.page = pagin.current;
        listQuery.page_size = pagin.pageSize;
        getList();
      }
      const listLoading = ref(false);
      const dataSource = ref([]);
      function getList() {
        listLoading.value = true;
        getModelAttrList(listQuery).then((res) => {
          ipagination.total = res.total;
          listLoading.value = false;
          dataSource.value = res.list;
        });
      }

      function batchUpload() {
        openBatchuploadd(true, {
          protocol_type: prop.protocol_type,
        });
      }
      //导入成功回调
      function importSuccess() {
        createMessage.success('导入成功');
        reloadTable();
      }
      //刷新Table
      function reloadTable() {
        listQuery.page = ipagination.current;
        listQuery.page_size = ipagination.pageSize;
        getList();
      }

      //点击分组查询属性列表
      async function cattap(e) {
        listData.value.filter((value) => {
          return value.id == e.target.value;
        });
        mrdriveId.value = e.target.value;
        listQuery.group_id = mrdriveId.value;
        reloadTable();
      }

      //删除分组
      function delGroup(id) {
        let obj = {
          id_list: [id],
        };
        createConfirm({
          iconType: 'info',
          title: '确定删除吗',
          onOk() {
            delAddModelGroup(obj).then((e) => {
              if (id == mrdriveId.value) {
                mrdriveId.value = undefined;
                reloadTable();
              }
              getGroupList();
              createMessage.success('删除成功');
            });
          },
        });
      }
      //打开添加分组弹框
      function addGroup() {
        openAttrGroupModal(true, {
          isUpdate: false,
        });
      }
      //打开添加分组弹框
      function editeGroup(rowData: Recordable) {
        openAttrGroupModal(true, {
          rowData,
          isUpdate: true,
        });
      }
      //打开编辑属性弹框
      function openEdit(Data: Recordable) {
        let rowData = Object.assign({}, Data, Data.rule);
        let data = {
          rowData: rowData,
          protocol_type: prop.protocol_type,
          isUpdate: true,
        };
        attributeDialogRef.value.addEdite(data);
      }
      //打开添加属性弹框
      function toAddAttr() {
        if (mrdriveId.value == undefined || mrdriveId.value == null) {
          createMessage.error('请选择分组');
          return false;
        }
        let data = {
          group_id: mrdriveId.value,
          protocol_type: protocol_type.value,
          isUpdate: false,
        };

        reloadDialog.value = false;
        reloadDialog.value = true;
        nextTick(() => {
          attributeDialogRef.value.addEdite(data);
        });
      }
      //添加修改成功回调
      function submitSuccess(e) {
        if (e.isGroup == false) {
          reloadTable();
        } else {
          getGroupList();
        }
        createMessage.success(e.isUpdate ? '修改成功' : '添加成功');
      }
      //删除属性
      function openDelete(rowData: [AttrGroupModel]) {
        const obj = {
          id_list: [],
        };
        obj.id_list.push(rowData.id);
        delModelAttrList(obj).then(() => {
          reloadTable();
        });
      }

      async function getGroupList() {
        let res = await getModelGroupList({
          device_mode_id: device_mode_id.value,
        });
        listData.value = res.list;
        if (res.list.length > 0) {
          mrdriveId.value = res.list[0].id;
          listQuery.group_id = mrdriveId.value;
          reloadTable();
        }
      }

      onBeforeMount(async () => {
        getGroupList();
      });
      return {
        listLoading,
        handleTableChange,
        ipagination,
        columns,
        dataSource,
        reloadDialog,
        attributeDialogRef,
        mrdriveId,
        getAttrList,
        listData,
        delGroup,
        getModelGroupList,
        getModelAttrList,
        tableData,
        registerAttrGroupModel,
        openAttrGroupModal,
        getAttrTableData,
        openEdit,
        toAddAttr,
        openDelete,
        addGroup,
        editeGroup,

        openBatchuploadd,
        registerBatchuploadd,
        submitSuccess,
        cattap,
        batchUpload,
        importSuccess,
        protocol_type,
      };
    },
  });
</script>

<style lang="less">
  .attrpage .ant-list-item-meta-title {
    display: flex;
    justify-content: space-between;
    box-sizing: border-box;
    align-items: center;
  }

  .attrpage .drive-list {
    width: 100%;
    min-height: 380px;
    display: flex;
    flex-direction: column;
    border: 1px solid #efefef;
    padding: 10px;
    box-sizing: border-box;
    overflow: hidden;
    overflow-x: hidden !important;
  }
  .attrpage .flexRow {
    width: 100%;
    display: flex;
    align-items: center;
    margin-bottom: 6px;
  }
  .attrpage .flexRow .flexc {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .attrpage .item_left {
    padding: 5px;
    box-sizing: border-box;
    width: 160px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    border: 1px solid #efefef;
  }
  .attrpage .item_right {
    flex: 1;
    display: flex;
  }

  .attrpage .item_right .groupedite {
    margin-left: 10px;
  }
  .attrpage .drive-head {
    display: flex;
    justify-content: space-between;
    .add-btn {
      cursor: pointer;
      text-decoration: underline;
    }
  }

  .add-attrs {
    cursor: pointer;
    display: flex;
    text-decoration: underline;
    .arritem {
      margin-left: 10px;
    }
  }
</style>
